package dao

import (
	"cld-quick-cli/database/models"
	"cld-quick-cli/pkg"
	"cld-quick-cli/router/parameters"
	"cld-quick-cli/setup"
	"errors"
	"fmt"
	"go.uber.org/zap"
)

/*
CheckUserExist 查询用户是否存在！
*/
func CheckUserExist(username string) (err error) {
	sqlStr := "select count(user_id) from user where username = ?"
	var count int
	err = setup.MysqlDB.Get(&count, sqlStr, username)
	// 如果执行有错误 或者 count > 0 那么就报错！
	if err != nil {
		zap.L().Error(err.Error())
		return err
	}
	if count > 0 {
		zap.L().Error("用户已经存在")
		return errors.New("用户已经存在")
	}
	return
}

// InsertUser 插入新用户！
func InsertUser(userId int64, user *parameters.SignUpNewUser) error {
	sqlStr := "insert into user (user_id,username,password) values (?,?,?)"
	hashedPassword, err := pkg.EncryptionPassword(user.RePassword)
	if err != nil {
		zap.L().Error(err.Error())
		return err
	}
	_, err = setup.MysqlDB.Exec(sqlStr, userId, user.Username, hashedPassword)
	if err != nil {
		zap.L().Error(err.Error())
		return err
	}
	return nil
}

// CheckUsernamePassword 根据 username 和 password 验证 用户！
func CheckUsernamePassword(username string, password string) (*models.UserModel, error) {
	var user models.UserModel
	sqlStr := "select user_id,username,password from user where username = ?"
	// 1.根据 username 查询用户
	err := setup.MysqlDB.Get(&user, sqlStr, username)
	if err != nil {
		zap.L().Error(err.Error())
		return nil, err
	}
	// 2.查到数据库中的用户密码！与明文密码做对比！
	if ok := pkg.ComparePasswords(user.Password, password); ok {
		return &user, nil
	} else {
		zap.L().Error("密码对比失败！")
		return nil, errors.New("用户名或密码错误！")
	}
}

func GetUserInfo(userId string) (*models.UserModel, error) {
	var um models.UserModel
	fmt.Println(userId)
	sqlStr := "select user_id,username,avatar,email,gender from user where user_id =  ?"
	err := setup.MysqlDB.Get(&um, sqlStr, userId)
	if err != nil {
		zap.L().Error(err.Error())
		return nil, errors.New("用户信息获取失败！")
	}
	return &um, nil
}
